package com.xudow.app.ui;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.models.base.SysStudentGrade;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.ui.task.GradesTask;
import com.xudow.app.ui.task.OrderStudentAddTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * 关联学生Activity
 *
 * @author lukecheng
 */
public class UserRelativeActivity extends BaseActivity {

    private static final int SCHOOL_SELECT = 1024;

    private Long orderId;

    private EditText usernameView, birthdayView, gradeView, schoolView;
    private RadioButton boyRadioButton, girlRadioButton;

    /**
     * 年级
     */
    private List<SysStudentGrade> grades;
    private GradesTask gradesTask;

    private Long gradeId;   //年级id
    private Long schoolId; //学校ID
    private String schoolName; //学校名字

    private OrderStudentAddTask orderStudentAddTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_relative);

        orderId = getIntent().getLongExtra("orderId", 0L);

        usernameView = (EditText) findViewById(R.id.username);
        birthdayView = (EditText) findViewById(R.id.birthday);
        gradeView = (EditText) findViewById(R.id.grade);
        schoolView = (EditText) findViewById(R.id.school);
        boyRadioButton = (RadioButton) findViewById(R.id.boy);
        girlRadioButton = (RadioButton) findViewById(R.id.girl);

        birthdayView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                new DatePickerDialog(UserRelativeActivity.this, dateSetListener, year, month, day).show();
            }
        });

        gradeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == grades || grades.size() < 0) {
                    showLodingDialog(getString(R.string.loading));

                    gradesTask = new GradesTask(UserRelativeActivity.this, gradesTaskHandler);
                    gradesTask.execute();
                } else {
                    showGradeDialog();
                }
            }
        });

        schoolView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserRelativeActivity.this, SysSchoolActivity.class);
                startActivityForResult(intent, SCHOOL_SELECT);
            }
        });
    }

    public void onBackBtnClick(View view) {
        setResult(RESULT_CANCELED);
        finish();
    }

    /**
     * 生日选择
     */
    private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, monthOfYear);
            cal.set(Calendar.DATE, dayOfMonth);

            birthdayView.setText(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
        }
    };

    private Handler gradesTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (GradesTask.SUCCESS == msg.what) {
                SysStudentGrade[] gradeArr = (SysStudentGrade[]) msg.getData().getSerializable("grades");

                grades = new ArrayList<SysStudentGrade>();
                grades.addAll(Arrays.asList(gradeArr));

                showGradeDialog();
            }
        }
    };

    /**
     * 显示年级选择对话框
     */
    private void showGradeDialog() {
        String[] gradeNames = new String[grades.size()];
        for (int i = 0; i < grades.size(); i++) {
            gradeNames[i] = grades.get(i).getName();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.grade_choose));
        builder.setSingleChoiceItems(gradeNames, 0, buttonOnClick);
        builder.create().show();
    }

    private DialogInterface.OnClickListener buttonOnClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which >= 0) {
                gradeView.setText(grades.get(which).getName());
                gradeId = grades.get(which).getId();

                dialog.dismiss();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            if (SCHOOL_SELECT == requestCode) {
                schoolName = data.getStringExtra("schoolName");
                schoolId = data.getLongExtra("schoolId", 0L);

                schoolView.setText(schoolName);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 确定按钮点击事件
     *
     * @param view
     */
    public void onCreateClick(View view) {
        String username = usernameView.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            usernameView.setError(getString(R.string.username_required));
            return;
        }

        String gender = "0";
        if (girlRadioButton.isChecked()) {
            gender = "1";
        }

        String birthday = birthdayView.getText().toString();
        if (TextUtils.isEmpty(birthday)) {
            birthdayView.setError(getString(R.string.birthday_required));
            return;
        }

        if (StringUtils.isEmpty(gradeView.getText().toString())) {
            gradeView.setError(getString(R.string.grade_required));
            return;
        }

        if (StringUtils.isEmpty(schoolView.getText().toString())) {
            schoolView.setError(getString(R.string.school_required));
            return;
        }

        showLodingDialog(getString(R.string.processing));

        HashMap<String, String> params = Maps.newHashMap();
        params.put("name", username);
        params.put("birthday", birthday);
        params.put("gender", gender);
        params.put("grade_id", "" + gradeId);
        params.put("school_id", "" + schoolId);
        params.put("order_id", "" + orderId);

        orderStudentAddTask = new OrderStudentAddTask(this, orderStudentAddTaskHandler);
        orderStudentAddTask.execute(params);
    }

    private Handler orderStudentAddTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (OrderStudentAddTask.SUCCESS == msg.what) {
                XApplication app = (XApplication) getApplication();
                app.closeChainActivities();

                String message = getString(R.string.order_student_select_success);
                Toast.makeText(UserRelativeActivity.this, message, Toast.LENGTH_SHORT).show();

                finish();
            } else {
                String message = getString(R.string.process_fail);
                Toast.makeText(UserRelativeActivity.this, message, Toast.LENGTH_SHORT).show();
            }
        }
    };
}
